﻿using System;
using System.Collections.Generic;
using Moq;
using Prompts.PromptServiceProxy;
using Prompts.Service.PromptService;

namespace Test.Prompts.Infrastructure.Fakes
{
    internal class FakePromptServiceClient
    {
        private readonly Mock<IPromptServiceClient> _promptServiceClient;
        private readonly Dictionary<string, object> _stateDictionary;

        public FakePromptServiceClient(Mock<IPromptServiceClient> promptServiceClient)
        {
            _promptServiceClient = promptServiceClient;
            _stateDictionary = new Dictionary<string, object>();
        }

        public void SetupGetPromptsAsync(string reportPath)
        {
            Func<object, bool> interceptStateFunc = o =>
            {
                if (!_stateDictionary.ContainsKey(reportPath))
                {
                    _stateDictionary.Add(reportPath, o);
                }

                return true;
            };

            _promptServiceClient.Setup(c => c.GetPromptsForReportAsync(
                reportPath
                , It.Is<object>(o => interceptStateFunc(o))));
        }

        public void RaiseGetPromptsCompleted(IEnumerable<PromptInfo> promptInfos, string reportPath)
        {
            var promptInfoCollection =
                new PromptInfoCollection
                {
                    ErrorMessage = string.Empty
                    ,
                    ErrorOccured = false
                    ,
                    Prompts = promptInfos
                };

            var wrapper = new object[] { promptInfoCollection };

            object state;
            _stateDictionary.TryGetValue(reportPath, out state);

            var args = new GetPromptsForReportCompletedEventArgs(wrapper, null, false, state);

            _promptServiceClient.Raise(c => c.GetPromptsForReportCompleted += null, args);
        }

        public void RaiseGetPromptsCompletedWithError(string errorMessage, string reportPath)
        {
            var promptInfoCollection =
                new PromptInfoCollection
                {
                    ErrorMessage = errorMessage
                    ,
                    ErrorOccured = true
                    ,
                    Prompts = new PromptInfo[] { }
                };

            var wrapper = new object[] { promptInfoCollection };

            object state;
            _stateDictionary.TryGetValue(reportPath, out state);

            var args = new GetPromptsForReportCompletedEventArgs(wrapper, null, false, state);

            _promptServiceClient.Raise(c => c.GetPromptsForReportCompleted += null, args);
        }
    }
}
